<template>
  <el-drawer v-model="dialogFormVisible" :with-header="false" size="80%">
    {{ $route.params.shopId }}
    <el-container class="layout-container-demo">
      <el-main>
        <el-scrollbar>
          <el-table :data="tableData">
            <el-table-column prop="id" label="编号" width="80" />
            <el-table-column prop="title" label="标题" width="120" />
            <el-table-column prop="wdescribe" label="描述" width="120" />
            <el-table-column prop="price" label="价格" width="60" />
            <el-table-column prop="number" label="数量" width="40" />
            <el-table-column prop="shippingAddressId" label="发货地id" width="80" />
            <el-table-column prop="shopId" label="商店id" width="60" />
            <el-table-column label="操作" width="350">
              <template #default="scope">
                <el-input-number v-model="scope.row.number" :min="1" />
                <el-button @click="deleteCommodity(scope.row.id)">删除</el-button>
                <el-checkbox v-model="scope.row.choose" label="选择" border />
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-main>
    </el-container>
    总计 {{ TotalNumber }} 总价{{ TotalAmount }}
    <el-button type="primary" style="margin-left: 16px" @click="openAddressDialog">
      选择地址下单
    </el-button>
    <address-choose ref="addressChooseRef" />
  </el-drawer>
</template>
  
<script lang="ts" setup>
import { ref, toRaw } from 'vue'
import { ElContainer } from 'element-plus';
import { mainStore } from "../../store/index";
import AddressChoose from './AddressChoose.vue';
const store = mainStore();

// 打开本ShopCart页
const dialogFormVisible = ref(false)
const openDialog = () => {
  dialogFormVisible.value = true
}
defineExpose({
  openDialog
})

// 打开地址选择页面
let addressChooseRef = ref()
const openAddressDialog = () => {
  //子组件方法
  addressChooseRef.value.openDialog();
}

//从pinia获取所有商品
let tableData = ref([])
const shoppingCart = toRaw(store.shoppingCart);
tableData.value = shoppingCart




// 计算数量与金额
let TotalNumber = ref(0);
let TotalAmount = ref(0);
watch(store.shoppingCart, (newVal, oldVal) => {
  let number: number = 0;
  let amout: number = 0;
  for (let i: number = 0; i < toRaw(newVal).length; i++) {
    number += toRaw(newVal)[i]?.number
    amout += toRaw(newVal)[i]?.number * toRaw(newVal)[i]?.price
  }
  TotalNumber.value = number;
  TotalAmount.value = amout;
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  immediate: true
})

watch(TotalAmount, (newVal, oldVal) => {
  store.totalPayment = TotalAmount.value
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  // immediate: true
})

// 删除购物车商品
const deleteCommodity = (commodityId: number) => {
  let index = store.shoppingCart.find(obj => obj.id === commodityId).index
  store.shoppingCart.splice(index, 1)
}


</script>
  
<style scoped></style>
  